import { Injectable } from '@angular/core';
import { Http, RequestOptions, Headers, Response } from '@angular/http';

@Injectable()
export class BasicService {

  public api = '/bod/api/v1/';
  public totalKey = 'totalResult';
  public dataKey = 'rows';
  public sortFieldKey = 'sort';
  public sortDirKey = 'order';
  public pagerPageKey = 'page';
  public pagerLimitKey = 'limit';
  public filterFieldKey = '#field#';

  private headers = new Headers({ 'Content-Type': 'application/json;charset=UTF-8' });

  private options = new RequestOptions({ 'headers': this.headers });

  constructor(public http: Http) {

  }

  // // 获得全部数据
  // getAll(url: string): Promise<any> {
  //   return this.http.get(this.api + url)
  //     .toPromise()
  //     .then(response => response.json() as any)
  //     .catch(this.handleError);
  // }
  // // 根据Id查询
  // getById(url: string, id: string): Promise<any> {
  //   return this.http.get(this.api + url + '?id=' + id)
  //     .toPromise().then(jsonStr => jsonStr.json() as any)
  //     .catch(this.handleError);
  // }

  // // 新增保存数据
  // save(url: string, data: Object): Promise<any> {
  //   return this.http.post(this.api + url, JSON.stringify(data), this.options)
  //     .toPromise()
  //     .then(response => response.json() as any)
  //     .catch(this.handleError);
  // }

  // // 更新数据
  // update(url: string, data: Object): Promise<any> {
  //   return this.http.put(this.api + url, JSON.stringify(data), this.options)
  //     .toPromise()
  //     .then(response => response.json() as any)
  //     .catch(this.handleError);
  // }

  // // 根据id删除数据
  // delete(url: string): Promise<any> {
  //   return this.http.delete(this.api + url)
  //     .toPromise()
  //     .then(response => response.json() as any)
  //     .catch(this.handleError);
  // }

  // // 捕获异常并输出
  // private handleError(error: any): Promise<any> {
  //   console.error('An error occurred', error); // for demo purposes only
  //   return Promise.reject(error.message || error);
  // }


  // Uses http.get() to load data from a single API endpoint
  getAll(url: string) {
    return this.http.get(this.api + url).map((res: Response) => res.json());
  }

  getOne(url: string) {
    return this.http.get(this.api + url).map((res: Response) => res.json());
  }

  create(url: string, data: Object) {
    const body = JSON.stringify(data);
    return this.http.post(this.api + url, body, this.options).map((res: Response) => res.json());
  }

  update(url: string, data: Object) {
    const body = JSON.stringify(data);
    return this.http.put(this.api + url, body, this.options).map((res: Response) => res.json());
  }

  delete(url: string) {
    return this.http.delete(this.api + url);
  }

}
